<template>
	<el-drawer v-model="visible" class="clue-detail-drawer" title="线索详情" :size="1200" :z-index="999" @close="onClose">
		<el-row v-loading="loading" :gutter="60" id="clueDetailDrawerBody">
			<el-col :span="13">
				<el-space>
					<!-- <a-image :width="80" src="https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png" /> -->
					<a-avatar shape="circle" :size="60">
						<template #icon><UserOutlined /></template>
					</a-avatar>
					<div style="margin-left: 10px">
						<div class="flex gap-3" style="margin-bottom: 10px">
							<span class="company-title">{{ detailInfo.customerName }}</span>
							<a-tag v-if="detailInfo.customerCode" color="blue" style="height: 24px; margin-right: 0">{{
								followUpMap[detailInfo.followUpStatus]
							}}</a-tag>
						</div>
						<a-tag v-if="detailInfo.customerType === 1" color="green">企业</a-tag>
						<a-tag v-if="detailInfo.customerType === 2" color="blue">自然人</a-tag>
					</div>
				</el-space>
				<div id="clueDetailPersonWrap" class="flex justify-between mt-[16px]">
					<div class="person-list flex-[6]">
						<div class="max-h-[150px] overflow-y-auto scrollbar-thumb">
							<div v-for="(item, index) in personList" :key="item.id" class="flex justify-start items-center my-1">
								<div class="w-[64px] mr-1 truncate" :title="item.contactsName">{{ item.contactsName || '---' }}</div>
								<div class="w-[64px] mr-1 truncate" :title="item.contactsPost">{{ item.contactsPost || '---' }}</div>
								<el-space size="small" class="phone-edit">
									<div class="mr-[2px]">
										手机：
										<a
											@click="
												callPhone(
													item.id,
													detailInfo.customerCode,
													item.contactsPhone,
													detailInfo.customerName,
													detailInfo.followUpStatus
												)
											"
										>
											<PhoneFilled style="transform: rotateY(180deg)" />{{ item.contactsPhone }}
										</a>
									</div>
									<el-icon
										v-if="hasPerm('bizCluePurposeDetailAddLinker')"
										size="18"
										color="#409eff"
										class="edit cursor-pointer"
									>
										<el-icon-Edit @click="editPerson(item)" />
									</el-icon>
									<el-icon
										v-if="hasPerm('bizCluePurposeDetailAddLinker') && index"
										size="18"
										color="#ff0000"
										class="edit cursor-pointer"
									>
										<el-icon-Delete @click="deletePerson(item)" />
									</el-icon>
								</el-space>
							</div>
						</div>
						<el-space v-if="hasPerm('bizCluePurposeDetailAddLinker')" :size="2" class="mt-2 cursor-pointer">
							<el-icon size="16" color="#409eff">
								<el-icon-Plus />
							</el-icon>
							<el-text type="primary" @click="addPerson">新增联系人</el-text>
						</el-space>
					</div>
					<div class="base-other flex-[4] ml-[10px]">
						<div class="text-gray-500 my-1">
							<span>跟进人</span>
							<span class="ml-[8px]">{{ detailInfo.followUpPerson || '---' }}</span>
						</div>
						<div class="text-gray-500 my-1">
							<span>最近跟进时间</span>
							<span class="ml-[8px]">{{ detailInfo.followUpTime || '---' }}</span>
						</div>
					</div>
				</div>
				<clue-detail-tab
					v-if="detailInfo.customerCode"
					ref="clueListTab"
					:info="detailInfo"
					type="CluePrivateSea"
					:getRecord="customerApi.getRecordList"
					:getPersonList="customerApi.getPersonList"
					@clueSave="getData"
				/>
			</el-col>
			<el-col :span="11">
				<div class="flex justify-around items-center mb-5">
					<drawer-step-space
						:prev-disabled="!detailInfo.prevId"
						:next-disabled="!detailInfo.nextId"
						@prev="() => onRefresh(detailInfo.prevId)"
						@next="() => onRefresh(detailInfo.nextId)"
					/>
					<el-button
						v-if="hasPerm('bizCluePurposeDetailAutoCall')"
						:type="store.autoDialStatus ? 'success' : 'danger'"
						style="padding: 20px 10px"
						plain
						@click="onAuthDialChange"
					>
						快速自动拨打<br />on/off
					</el-button>
					<div v-else></div>
				</div>

				<a-form layout="vertical" :label-col="{ style: { width: '100px' } }" class="form_label">
					<a-form-item label="线索等级">
						<a-select
							v-model:value="levelId"
							:options="levelOptions"
							placeholder="请选择等级"
							:disabled="!hasPerm('bizCluePurposeDetailEdit')"
							@change="levelChange"
						></a-select>
					</a-form-item>
				</a-form>
				<a-form layout="vertical" :label-col="{ style: { width: '100px' } }" class="form_label">
					<a-form-item label="跟进内容">
						<el-space class="mb-4">
							<a-select
								v-model:value="followUpPerson"
								show-search
								placeholder="选择或搜索联系人"
								:options="personOptions"
								style="width: 160px"
								label-in-value
								:filter-option="false"
								@search="personSearch"
							></a-select>
							<a-select
								v-model:value="followForm.followType"
								:options="followOptions"
								placeholder="选择跟进方式"
								class="w-[170px]"
							>
							</a-select>
							<div class="flex justify-between items-center">
								<span class="px-1">是否添加微信</span>
								<a-radio-group v-model:value="followForm.is_wx_code" button-style="solid">
									<a-radio :value="1">是</a-radio>
									<a-radio :value="0">否</a-radio>
								</a-radio-group>
							</div>
						</el-space>
						<el-input
							v-model="followForm.content"
							:rows="5"
							type="textarea"
							maxlength="200"
							:show-word-limit="true"
							placeholder="请输入跟进内容"
						/>
						<div class="mt-3 text-right">
							<el-button
								:disabled="!hasPerm('bizCluePurposeDetailFollowIn')"
								type="primary"
								plain
								@click="followUpSubmit"
								>添加跟进记录</el-button
							>
						</div>
					</a-form-item>
				</a-form>

				<div class="tag-wrap">
					<h4>线索标签</h4>
					<div class="scroll-section scrollbar-thumb">
						<template v-if="tagData.length">
							<el-checkbox-group
								v-if="hasPerm('bizCluePurposeDetailAddTag')"
								v-model="tagIdList"
								size="small"
								@change="tagChange"
							>
								<div v-for="(item, index) in tagData" :key="index" class="tag-group">
									<div class="tag-title">{{ item.groupName }}</div>
									<el-space wrap>
										<el-checkbox-button
											v-for="(itemVal, indexVal) in item.list"
											:key="`${index}-${indexVal}`"
											:value="itemVal.id"
										>
											{{ itemVal.labelName }}
										</el-checkbox-button>
									</el-space>
								</div>
							</el-checkbox-group>
							<template v-else>
								<div v-for="(item, index) in tagData" :key="index" class="tag-group-show">
									<div class="tag-title">{{ item.groupName }}</div>
									<el-space wrap>
										<template v-for="(itemVal, indexVal) in item.list" :key="`${index}-${indexVal}`">
											<el-tag type="primary" :effect="tagIdList.includes(itemVal.id) ? 'dark' : 'plain'">
												{{ itemVal.labelName }}
											</el-tag>
										</template>
									</el-space>
								</div>
							</template>
						</template>
						<el-empty v-else description="暂无标签" />
					</div>
				</div>

				<el-space class="mt-10">
					<el-button :disabled="!hasPerm('bizCluePurposeDetailRecycle')" type="danger" plain @click="onRecycle"
						>回收公海</el-button
					>
					<el-button
						:disabled="!hasPerm('bizCluePurposeDetailTransferClue')"
						type="primary"
						plain
						@click="onTransferClue"
						>转让线索</el-button
					>
					<el-button :disabled="!hasPerm('bizCluePurposeDetailTransfer')" type="primary" @click="onTransfer"
						>转客户</el-button
					>
				</el-space>
			</el-col>
		</el-row>
	</el-drawer>

	<!-- 联系人弹窗 -->
	<person-modal
		v-if="personVisible"
		v-model:visible="personVisible"
		:customerCode="detailInfo.customerCode"
		:info="personInfo"
		:type="type"
		@finished="getPersonList"
	/>
</template>

<script setup>
	import customerApi from '@/api/biz/customerApi'
	import claimApi from '@/api/biz/claimApi'
	import useTableFilter from '@/hook/useTableFilter'
	import { followUpMap } from '@/views/biz/contractManagement/enum/contractEnum'
	import clueDetailTab from './clueDetailTab.vue'
	import personModal from './personModal.vue'
	import recoveryModal from './recoveryModal.vue'
	import followModal from '../claimList/followModal.vue'

	import { ewaytelStore, globalStore } from '@/store'
	import customerLevelApi from '@/api/biz/crm/customerLevelApi'
	import tool from '@/utils/tool'
	import { message, Modal } from 'ant-design-vue'
	import tagApi from '@/api/biz/tagApi'

	const tableFilter = useTableFilter('clueManagementFilter')

	const emits = defineEmits(['finishTag', 'recycle', 'transferClue', 'transfer'])

	const store = globalStore()
	const ewaytel = ewaytelStore()

	const visible = ref(false)
	const onClose = () => {
		store.autoDialStatus = false
		detailInfo.value = {
			id: null,
			customerCode: null,
			prevId: null,
			nextId: null
		}
		store.dashboardNode?.setDialWait(0)
	}

	const loading = ref(false)

	const type = ref(4) // 线索私海

	const onRefresh = async (id) => {
		detailInfo.value = { id }
		await requestData()
	}

	const autoDialStepFn = () => {
		nextTick(() => {
			if (store.autoDialStatus && !loading.value) {
				const { code } = store.dashboardNode?.phoneData || {}
				if (code === detailInfo.value.customerCode) {
					refreshNext()
				} else {
					autoDialFn()
				}
			}
		})
	}
	const dialLineStatus = computed(() => store.phoneStatus)
	watch(dialLineStatus, (newVal, oldVal) => {
		if (!newVal && oldVal) {
			autoDialStepFn()
		}
	})
	const dial4GStatus = computed(() => ewaytel.talkState)
	watch(dial4GStatus, (newVal, oldVal) => {
		if (newVal === 'idle' && oldVal === 'hangup') {
			autoDialStepFn()
		}
	})
	const autoDialFn = () => {
		if (store.autoDialStatus) {
			if (ewaytel.configs.communicationTypeSwitch) {
				store.autoDialStatus = false
				return message.warning('请先开启通讯方式，并设置4G多卡话机拨号')
			} else {
				if (!ewaytel.configs.communicationType) {
					store.autoDialStatus = false
					return message.warning('请先设置通讯方式为4G多卡话机拨')
				}
			}

			if (!store.dashboardNode?.visible) {
				store.dashboardNode.visible = true
			}

			const dialPhoneFn = () => {
				const { id, contactsPhone } = personList.value[0]
				const { customerCode, customerName, followUpStatus } = detailInfo.value
				callPhone(id, customerCode, contactsPhone, customerName, followUpStatus)
			}
			if (
				(store.isLineCall && !store.phoneStatus) ||
				(store.is4GCall && ewaytel.isTalkIdle && ewaytel.telInstance?.actionType)
			) {
				if (ewaytel.isConnecting) {
					const timer = setInterval(() => {
						if (ewaytel.isConnectSuccess) {
							clearInterval(timer)
							dialPhoneFn()
						}
					}, 500)
				}
				if (ewaytel.isConnectSuccess) {
					dialPhoneFn()
				}
			}
		}
	}

	const onAuthDialChange = () => {
		store.autoDialStatus = !store.autoDialStatus
		store.dashboardNode?.setDialWait(store.autoDialStatus ? 1200 : 0)
		autoDialFn()
	}

	const detailInfo = ref({
		id: null,
		customerCode: null,
		prevId: null,
		nextId: null
	})
	const getData = async () => {
		const filterData = tableFilter.get() || {}
		detailInfo.value = await customerApi.getClueDetail({ id: detailInfo.value.id, ...filterData })
		levelId.value = detailInfo.value.customerLevelId
	}

	/**
	 * 公司人员
	 */
	const personData = ref([])
	const getCompanyPersonList = () => {
		const param = {
			code: detailInfo.value.customerCode
		}
		claimApi.getCompanyPersons(param).then((res) => {
			personData.value = res
			const { id, contactsName } = res[0]
			followUpPerson.value = { label: contactsName || '---', value: id }
		})
	}

	/**
	 * 联系人
	 */
	const personList = ref([])
	const getPersonList = async () => {
		const params = {
			code: detailInfo.value.customerCode,
			type: type.value
		}
		personList.value = await customerApi.getCluePersonList(params)
	}

	/**
	 * 拨号
	 * @param {*} code customercode
	 * @param {*} id 联系人记录id
	 * @param {*} phone 手机号
	 * @param {*} name 名称
	 * @param {*} status 状态
	 */
	const callPhone = (id, code, phone, name, status) => {
		store.dashboardNode?.open({ id, code, phone, name, type: type.value, status })
		nextTick(() => {
			if (store.dashboardNode?.phoneData.code === code) {
				store.tagIdList = tagIdList.value
				store.tagNameList = tagNameList.value
			}
		})
	}

	/**
	 * 联系人
	 */
	const personVisible = ref(false)
	const personInfo = ref({})
	const addPerson = () => {
		personInfo.value = {}
		personVisible.value = true
	}
	const editPerson = (data) => {
		personInfo.value = {
			id: data.id,
			contactsPhone: data.contactsPhone,
			contactsName: data.contactsName,
			contactsPost: data.contactsPost,
			phone: data.phone
		}
		personVisible.value = true
	}
	const deletePerson = (data) => {
		Modal.confirm({
			title: '提示',
			content: '确认删除吗?',
			okText: '确认',
			onOk: () => {
				customerApi
					.deleteContacts({ id: data.id, type: type.value, customerCode: detailInfo.value.customerCode })
					.then(() => {
						message.success('删除成功')
						getPersonList()
					})
			},
			closable: true,
			cancelText: '取消'
		})
	}

	/**
	 * tabs
	 */
	const clueListTab = ref(null)

	/**
	 * 获取客户等级选项
	 */
	const levelId = ref(null)
	const tempLevelId = ref(null)
	const levelOptions = ref([])
	customerLevelApi.list().then((res) => {
		levelOptions.value = res.map((item) => {
			return {
				value: item.id,
				label: item.name
			}
		})
	})
	const levelChange = (select, option) => {
		customerApi
			.setClueLevel({
				id: detailInfo.value.id,
				type: type.value,
				customerLevelId: select,
				customerLevelName: option.label
			})
			.then(() => {
				tempLevelId.value = select
			})
			.catch((err) => {
				levelId.value = tempLevelId.value
			})
	}

	/**
	 * 跟进
	 * @param id
	 * @returns {Promise<void>}
	 */
	const followLoading = ref(false)
	const followOptions = tool.dictList('FOLLOW')
	const followForm = ref({
		customerCode: null,
		userId: null,
		userName: null,
		followType: followOptions[0].value,
		is_wx_code: 0,
		content: null,
		type: type.value
	})
	const personOptions = computed(() =>
		personData.value.map((item) => ({ value: item.id, label: item.contactsName || '---' }))
	)
	const followUpPerson = computed({
		get: () => {
			const { userId, userName } = followForm.value
			if (userId) {
				return { label: userName, value: userId }
			}
			return null
		},
		set: (value) => {
			followForm.value.userId = value.value
			followForm.value.userName = value.label
		}
	})
	const personSearch = (val) => {
		personOptions.value = personOptions.value.filter((item) => item.label.includes(val))
	}
	const followUpSubmit = () => {
		const { userId, followType } = followForm.value
		if (!userId) {
			return message.warning('请选择联系人')
		}
		if (!followType) {
			return message.warning('请选择跟进方式')
		}

		followForm.value.customerCode = detailInfo.value.customerCode

		followLoading.value = true
		claimApi
			.transferToCustomer(followForm.value)
			.then(() => {
				clueListTab.value?.getRecords()

				const { id, contactsName } = personData.value[0]
				followForm.value = {
					customerCode: null,
					userId: id,
					userName: contactsName || '---',
					followType: followOptions[0].value,
					is_wx_code: 0,
					content: null,
					type: type.value
				}
			})
			.finally(() => {
				followLoading.value = false
			})
	}

	/**
	 * 标签
	 */
	const tagIdList = ref([])
	const tagNameList = ref([])
	const tagData = ref([])
	const getTagTreeList = () => {
		tagApi
			.tagTreeList({
				type: 1 // 0或null-全部 1-线索 2-客户
			})
			.then((res) => {
				tagData.value = res
			})
	}
	const getTagList = async () => {
		const res = await customerApi.getTagList({
			customerCode: detailInfo.value.customerCode
		})
		const { labelId, labelName } = res
		if (labelName) {
			tagIdList.value = labelId.split(',')
			tagNameList.value = labelName.split(',')
		} else {
			tagIdList.value = []
			tagNameList.value = []
		}
	}
	const tagChange = () => {
		customerApi
			.addTag({
				customerCode: detailInfo.value.customerCode,
				type: type.value,
				ids: tagIdList.value
			})
			.finally(() => {
				initRequestTagData()
			})
	}

	const tagFinishStatus = computed(() => store.tagFinishStatus)
	const initRequestTagData = async () => {
		if (visible.value) {
			await getTagList()
			clueListTab.value?.getRecords()
			nextTick(() => {
				if (store.dashboardNode?.phoneData.code === detailInfo.value.customerCode) {
					store.tagIdList = tagIdList.value
					store.tagNameList = tagNameList.value
				}
			})
		}
		emits('finishTag')
	}
	watch(tagFinishStatus, (newVal, oldVal) => {
		if (newVal) {
			initRequestTagData()
		}
	})

	/**
	 * 回收公海
	 */
	const onRecycle = () => {
		emits('recycle', detailInfo.value)
	}

	/**
	 * 转让线索
	 */
	const onTransferClue = () => {
		emits('transferClue', detailInfo.value)
	}

	const onTransfer = () => {
		emits('transfer', detailInfo.value)
	}

	const requestData = async () => {
		try {
			loading.value = true
			await getData()
			await getPersonList()
			await getCompanyPersonList()
			await getTagTreeList()
			await getTagList()

			autoDialFn()
		} finally {
			loading.value = false
		}
	}

	const refreshNext = () => {
		if (detailInfo.value.nextId) {
			onRefresh(detailInfo.value.nextId)
		} else {
			visible.value = false
		}
	}

	const open = (id) => {
		detailInfo.value.id = id
		visible.value = true
		requestData()
	}

	defineExpose({
		visible,
		open,
		refreshNext
	})
</script>

<style lang="less">
	.clue-detail-drawer .el-drawer__header {
		margin-bottom: 0;
	}
	.clue-detail-drawer .el-drawer__body {
		padding: 20px 30px;
	}
</style>
<style scoped lang="less">
	.scroll-section {
		//max-height: 280px;
		overflow-y: auto;
	}

	.tag-group {
		margin-top: 10px;
		padding-top: 26px;
		.tag-title {
			position: relative;
			top: -14px;
			font-size: 14px;
		}
	}
	.tag-group-show {
		margin-top: 10px;
		.tag-title {
			margin-bottom: 5px;
		}
	}

	.phone-edit {
		.edit {
			display: none;
		}
		&:hover {
			.edit {
				display: block;
			}
		}
	}
</style>
